import { login, getInfo, loginByCode } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

import { handleThemeStyle } from '@/utils/theme'
import useSettingsStore from '@/store/modules/settings'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      loginName: ''
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        return new Promise((resolve, reject) => {
          login(username, password).then(res => {
            setToken(res.data.token)
            this.token = res.data.token
            // this.loginName = res.data.userName
            
            window.sessionStorage.setItem('userName', res.data.userName)
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      loginByCode(userInfo) {
        const username = userInfo.username.trim()
        const smscode = userInfo.smscode.trim()
        const data = {
          username,
          smscode
        }
        return new Promise((resolve, reject) => {
          loginByCode(data).then(res => {
            setToken(res.token)
            this.token = res.token
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          if (window.sessionStorage.getItem('userName')) {
            this.loginName = window.sessionStorage.getItem('userName')
          }
          getInfo({ UserName: this.loginName }).then(res => {
            const { data: user } = res

            if (user && user?.id) {
              localStorage.setItem('userId', user.id)
              localStorage.setItem('user', JSON.stringify(user))
            }
            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.id = user.userId
            this.name = user.schoolName
            this.avatar =  '@/assets/images/profile.jpg'

            // 设置系统默认主题色
            useSettingsStore().changeSetting({
              key: 'theme',
              value: user.themeColor
            })

            handleThemeStyle(user.themeColor)
            console.log(useSettingsStore().theme, 73)
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          this.token = ''
          this.roles = []
          this.permissions = []
          removeToken()
          resolve()
        })
      }
    }
  })

export default useUserStore
